<template>
  <x-page class="flex-row">
    <div class="left-panel">
      <div class="top">
        <el-dropdown style="margin-right: 15px" @command="handleCommand" v-hasPermi="['upms:menu:add']">
          <el-button type="primary" plain>
            {{ $t('auth.menu.newMenu') }}<em class="el-icon-arrow-down el-icon--right"></em>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="a">{{ $t('auth.menu.newFiles') }}</el-dropdown-item>
            <el-dropdown-item command="b">{{ $t('auth.menu.newSub') }}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <!-- <el-button type="primary" plain @click="handleExpand"
          ><em class="el-icon-s-operation"></em>{{ isExpanded ? '全部收起' : '全部展开' }}</el-button
        > -->
      </div>
      <div class="tree-container">
        <div class="search-input-container">
          <el-input
            prefix-icon="el-icon-search"
            :placeholder="$t('common.treeFilter')"
            v-model="filterText"
            style="margin-bottom: 5px"
            clearable
          >
          </el-input>
          <module-select ref="selectModuleCom" @on-change="refreshTree" />
        </div>

        <el-scrollbar
          style="height: calc(100% - 60px)"
          v-loading="loading"
          :element-loading-text="$t('common.loading')"
          element-loading-spinner="el-icon-loading"
        >
          <el-tree
            :props="treeProps"
            ref="tree"
            default-expand-all
            :highlight-current="true"
            node-key="id"
            :filter-node-method="filterNode"
            :expand-on-click-node="false"
            :data="menuTreeData"
            :render-content="renderContent"
            @node-click="handleNodeClick"
          ></el-tree>
        </el-scrollbar>
      </div>
    </div>
    <div class="right-panel">
      <el-tabs v-model="activeName">
        <el-tab-pane :label="$t('auth.menu.baseInfo')" name="first">
          <el-alert :title="$t('auth.menu.alertTips')" type="info" show-icon style="margin-bottom: 10px"> </el-alert>
          <menu-add
            ref="menuAddComponent"
            :dict-options="dictOptions"
            :menu-tree-data="menuTreeData"
            :menu-info="currentNode"
            :client-id="currentClient"
            :defaultMenuProps="treeProps"
            @handleSuccess="loadTreeData"
            @handleDelSuccess="
              currentNode = null
              loadTreeData()
            "
          ></menu-add>
        </el-tab-pane>
        <el-tab-pane :label="$t('auth.menu.btns')" name="second">
          <menu-btn-info
            ref="menuBtnInfoComponent"
            :dict-options="dictOptions"
            :client-id="currentClient"
            @handleSuccess="loadTreeData"
          />
        </el-tab-pane>
      </el-tabs>
    </div>
    <x-dialog :title="$t('auth.menu.addMens')" :show.sync="visible" v-if="visible" width="45%">
      <menu-add
        ref="subMenuAddComponent"
        v-if="visible"
        :menu-tree-data="menuTreeData"
        :dict-options="dictOptions"
        :defaultMenuProps="treeProps"
        :client-id="currentClient"
        :isShowFooter="false"
        @handleSuccess="
          visible = false
          loadTreeData()
        "
        :menu-info="addInfo"
      ></menu-add>
      <span slot="footer">
        <el-button @click="handleCancel">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button
          type="primary"
          @click="
            btnLoading = true
            handleSubmit()
          "
          :loading="btnLoading"
        >
          {{ $t('common.save') }}
        </el-button>
      </span>
    </x-dialog>
  </x-page>
</template>
<script lang="jsx">
  import { omit, QueryDictMixin, PermissionsMixin } from '@package/utils'
  // import { QueryDictMixin, PermissionsMixin } from '@/common/mixins'
  import { mapState } from 'pinia'
  import { pinias } from '@/common/pinia'
  import { columns } from '../config/menuConfig.js'
  import { apiDeleteMenu, apiGetMenuTree } from '../api'
  import MenuAdd from '../components/menuAdd.vue'
  import menuBtnInfo from '../components/menuBtnInfo.vue'
  import ModuleSelect from '../components/moduleSelect.vue'
  import { EnumApiCode } from '../../../../../../globalEnum'

  const { cachedView } = pinias
  export default {
    name: 'Menu',
    components: {
      MenuAdd,
      menuBtnInfo,
      ModuleSelect
    },
    mixins: [QueryDictMixin, PermissionsMixin],
    data() {
      return {
        filterText: '',
        isExpanded: false,
        columns,
        activeName: 'first',
        currentNode: {},
        menuTreeData: [],
        statusOptions: [],
        tableColumns: [],
        treeProps: {
          label: 'menuName',
          children: 'children'
        },
        visible: false,
        addInfo: {},
        dictKeys: ['system.state', 'upms_menu.menu_type'],
        btnLoading: false,
        loading: false,
        creatFlage: false,
        currentClient: ''
      }
    },
    computed: {
      ...mapState(cachedView, ['visitedViews'])
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val)
      }
    },
    created() {
      this.creatFlage = true
      // this.loadTreeData()
      this.initDictConfig()
    },
    // activated() {
    //   const temp = this.visitedViews.filter((v) => v.path === this.$route.path)
    //   if (this.creatFlage && !temp) {
    //     this.loadTreeData()
    //     this.initDictConfig()
    //   }
    // },
    methods: {
      refreshTree(val) {
        this.currentClient = val
        this.currentNode = {}
        this.loading = true
        this.loadTreeData()
      },
      loadTreeData() {
        this.loading = true
        apiGetMenuTree({ menuTypes: [1, 2], clientId: this.currentClient })
          .then(({ code, msg, data }) => {
            this.loading = false
            if (code === EnumApiCode.Success) {
              this.menuTreeData = []
              this.menuTreeData = data
              if (this.menuTreeData?.length) {
                this.setComponentsInfo()
              } else {
                this.currentNode = {}
              }
            } else {
              this.$message.error(msg)
            }
          })
          .catch(() => {
            this.loading = false
          })
      },
      setComponentsInfo() {
        this.$nextTick(() => {
          const currentKey = this.currentNode?.id ?? this.menuTreeData[0].id
          this.currentNode = this.$refs.tree.getNode(currentKey)?.data
          if (!this.currentNode?.id) {
            this.currentNode = this.$refs.tree.getNode(this.menuTreeData[0].id)?.data
          }
          this.currentNode = omit(this.currentNode, 'children')
          if (this.currentNode?.id) {
            this.$refs.tree.setCurrentKey(this.currentNode.id)
            this.$refs.menuBtnInfoComponent.loadData(this.currentNode.id)
          }
        })
      },
      handleCommand(command) {
        this.visible = true
        this.$nextTick(() => {
          this.addInfo = {
            parentId: command === 'a' ? '0' : this.currentNode.id,
            menuType: command === 'a' ? '1' : '2'
          }
        })
      },
      handleSubmit() {
        this.$refs.subMenuAddComponent.handleSubmit().then(
          () => {
            this.btnLoading = false
            this.visible = false
          },
          () => {
            this.btnLoading = false
          }
        )
      },
      handleCancel() {
        this.$refs.subMenuAddComponent.handleClose()
        this.visible = false
      },
      handleNodeClick(data, node, ele) {
        this.currentNode = data
        this.activeName = 'first'
        this.setComponentsInfo()
      },
      filterNode(value, data) {
        if (!value) return true
        return data[this.treeProps.label].indexOf(value) !== -1
      },
      renderContent(h, { node, data, store }) {
        return (
          <span className="custom-tree-node">
            <span>{node.label}</span>
            <span>
              {/* <el-button size="mini" type="text" on-click={() => this.append(data)}>
                  Append
                </el-button>
                <el-button size="mini" type="text" on-click={() => this.remove(node, data)}>
                  Delete
                </el-button> */}
            </span>
          </span>
        )
      },
      handleActions({ key, data }) {
        switch (key) {
          case 'add':
            this.$refs.menuAddComponent.handleOpen(data, 'add')
            break
          case 'delete':
            this.$confirm(this.$t('auth.menu.deletePrmo'), this.$t('auth.menu.prompt'), {
              confirmButtonText: this.$t('common.sure'),
              cancelButtonText: this.$t('common.cancel'),
              type: 'warning'
            })
              .then((confirm) => {
                this.handleDeleteMenu(data.menuId)
              })
              .catch((cancel) => {})
            break
          case 'edit':
            this.$refs.menuAddComponent.handleOpen(data)
            break
          default:
            break
        }
      },
      handleAddMenu() {
        this.$refs.menuAddComponent.handleOpen()
      },
      async handleDeleteMenu(infoId) {
        const { code, msg } = await apiDeleteMenu(infoId)
        if (code === EnumApiCode.Success) {
          this.$message.success(this.$t('auth.role.successTips'))
          this.loadTreeData()
        } else {
          this.$message.error(msg)
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import '../../../common/assets/style/variables';

  .flex-row {
    display: flex;
    flex-direction: row;

    .left-panel {
      flex: 1;
      min-width: 300px;
      border-radius: 3px;
      background-color: $x-default-bg-color;

      .top {
        margin-bottom: 16px;
        padding: 12px 15px;
        border-bottom: 1px solid #e0e0e0;
      }

      .tree-container {
        height: calc(100% - 100px);
        .search-input-container {
          padding: 0 15px;
        }
      }
    }

    .right-panel {
      flex: 5;
      max-width: calc(100% - 300px);
      margin-left: 10px;
      padding: 15px;
      border-radius: 3px;
      background-color: $x-default-bg-color;

      .el-tabs.el-tabs--top {
        height: 100%;
      }

      .info-container {
        padding: 0 15px;
      }

      .menu-info-hearder {
        font-size: 16px;
        line-height: 60px;
        margin-bottom: 10px;
        padding-left: 15px;
        color: $x-item-text-color;
        border-bottom: 1px solid #e0e0e0;

        .el-icon-edit-outline {
          font-size: 18px;
          vertical-align: middle;
        }
      }
    }
  }
  ::v-deep.right-panel .el-tabs__content {
    height: calc(100% - 55px);
    .el-tab-pane {
      height: 100%;
    }
  }
</style>
<style lang="scss">
  /* element滚动条组件 隐藏水平滚动条 */
  .tree-container .el-scrollbar__view {
    padding: 0 15px;
  }

  .tree-container .el-scrollbar__wrap {
    overflow-x: hidden;
  }

  .is-horizontal {
    display: none;
  }
  ::v-deep.tree-select .el-input__inner {
    border-width: 0px !important;
  }
</style>
